<template>
  <div class="user-data-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="个人数据管理"
      left-arrow
      @click-left="$router.back()"
      class="custom-nav-bar"
    />

    <!-- 用户信息卡片 -->
    <div class="user-info-card">
      <div class="user-avatar">
        <img v-if="userInfo?.avatar" :src="userInfo.avatar" alt="头像" />
        <van-icon v-else name="user-o" size="40" />
      </div>
      <div class="user-details">
        <h3>{{ userInfo?.nickname || userInfo?.username || '未知用户' }}</h3>
        <p>用户ID: {{ userInfo?.id || userInfo?.userId || 'N/A' }}</p>
        <p>邮箱: {{ userInfo?.email || '未设置' }}</p>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="data-stats">
      <h3>📊 数据统计</h3>
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-number">{{ dataStats.totalKeys }}</div>
          <div class="stat-label">数据项</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ dataStats.features.length }}</div>
          <div class="stat-label">功能模块</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ formatDataSize(dataStats.totalSize) }}</div>
          <div class="stat-label">存储大小</div>
        </div>
      </div>
    </div>

    <!-- 功能数据列表 -->
    <div class="feature-data-list">
      <h3>🗂️ 功能数据</h3>
      <div v-if="dataStats.features.length === 0" class="empty-data">
        <div class="empty-icon">📭</div>
        <p>暂无个人数据</p>
        <p class="empty-tip">使用AI功能后会自动保存您的个人数据</p>
      </div>
      <div v-else class="feature-cards">
        <div
          v-for="feature in featureDataList"
          :key="feature.name"
          class="feature-card"
          @click="showFeatureDetail(feature)"
        >
          <div class="feature-icon">{{ feature.icon }}</div>
          <div class="feature-info">
            <h4>{{ feature.displayName }}</h4>
            <p>{{ feature.dataCount }} 项数据</p>
            <p class="feature-size">{{ formatDataSize(feature.size) }}</p>
          </div>
          <van-icon name="arrow" />
        </div>
      </div>
    </div>

    <!-- 数据管理操作 -->
    <div class="data-actions">
      <h3>⚙️ 数据管理</h3>
      <div class="action-buttons">
        <van-button
          type="primary"
          block
          @click="exportAllData"
          :loading="isExporting"
        >
          📥 导出所有数据
        </van-button>
        <van-button
          type="warning"
          block
          @click="showClearConfirm"
          :disabled="dataStats.totalKeys === 0"
        >
          🗑️ 清空所有数据
        </van-button>
      </div>
    </div>

    <!-- 功能详情弹窗 -->
    <van-popup v-model:show="showDetailPopup" position="bottom" :style="{ height: '70%' }">
      <div class="detail-popup">
        <div class="popup-header">
          <h3>{{ selectedFeature?.displayName }} 数据详情</h3>
          <van-button size="small" @click="showDetailPopup = false">关闭</van-button>
        </div>
        <div class="popup-content">
          <div v-if="selectedFeature" class="feature-detail">
            <div class="detail-stats">
              <div class="detail-stat">
                <span class="label">数据项数量:</span>
                <span class="value">{{ selectedFeature.dataCount }}</span>
              </div>
              <div class="detail-stat">
                <span class="label">存储大小:</span>
                <span class="value">{{ formatDataSize(selectedFeature.size) }}</span>
              </div>
              <div class="detail-stat">
                <span class="label">最后更新:</span>
                <span class="value">{{ selectedFeature.lastUpdate }}</span>
              </div>
            </div>

            <div class="data-types">
              <h4>数据类型</h4>
              <div class="type-list">
                <div
                  v-for="type in selectedFeature.dataTypes"
                  :key="type.name"
                  class="type-item"
                >
                  <span class="type-name">{{ type.displayName }}</span>
                  <span class="type-count">{{ type.count }} 项</span>
                </div>
              </div>
            </div>

            <div class="feature-actions">
              <van-button
                type="primary"
                size="small"
                @click="exportFeatureData(selectedFeature.name)"
              >
                导出数据
              </van-button>
              <van-button
                type="danger"
                size="small"
                @click="clearFeatureData(selectedFeature.name)"
              >
                清空数据
              </van-button>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { getUserInfo } from '@/utils/auth'
import {
  getCurrentUserId,
  getUserDataStats,
  getUserDataKeys,
  formatDataSize,
  clearFeatureData as clearFeatureDataUtil,
  loadUserData
} from '@/utils/userDataManager'

// 响应式数据
const userInfo = ref<any>(null)
const dataStats = ref({
  totalKeys: 0,
  features: [],
  dataTypes: [],
  totalSize: 0
})
const showDetailPopup = ref(false)
const selectedFeature = ref<any>(null)
const isExporting = ref(false)

// 功能配置
const featureConfig = {
  knowledgeQA: { displayName: '知识问答', icon: '🧠' },
  informationQuery: { displayName: '信息查询', icon: '🔍' },
  textGeneration: { displayName: '文本生成', icon: '✍️' },
  translation: { displayName: '语言翻译', icon: '🌐' },
  recommendation: { displayName: '智能推荐', icon: '🎯' },
  emotionalCompanion: { displayName: '情感陪伴', icon: '💜' },
  gameEntertainment: { displayName: '游戏娱乐', icon: '🎮' },
  healthManagement: { displayName: '健康管理', icon: '❤️' }
}

const dataTypeConfig = {
  history: { displayName: '历史记录' },
  favorites: { displayName: '收藏夹' },
  settings: { displayName: '设置' },
  darkMode: { displayName: '深色模式' },
  searchHistory: { displayName: '搜索历史' },
  chatHistory: { displayName: '聊天历史' },
  selectedTags: { displayName: '兴趣标签' }
}

// 计算属性
const featureDataList = computed(() => {
  return dataStats.value.features.map(featureName => {
    const config = featureConfig[featureName as keyof typeof featureConfig]
    const userKeys = getUserDataKeys()
    const featureKeys = userKeys.filter(key => key.includes(`_${featureName}_`))

    let totalSize = 0
    const dataTypes: any[] = []

    featureKeys.forEach(key => {
      const data = localStorage.getItem(key)
      if (data) {
        totalSize += data.length

        // 解析数据类型
        const parts = key.split('_')
        if (parts.length >= 3) {
          const dataType = parts[2]
          const typeConfig = dataTypeConfig[dataType as keyof typeof dataTypeConfig]
          if (typeConfig) {
            const existingType = dataTypes.find(t => t.name === dataType)
            if (existingType) {
              existingType.count++
            } else {
              dataTypes.push({
                name: dataType,
                displayName: typeConfig.displayName,
                count: 1
              })
            }
          }
        }
      }
    })

    return {
      name: featureName,
      displayName: config?.displayName || featureName,
      icon: config?.icon || '📁',
      dataCount: featureKeys.length,
      size: totalSize,
      dataTypes,
      lastUpdate: getLastUpdateTime(featureKeys)
    }
  })
})

// 获取最后更新时间
const getLastUpdateTime = (keys: string[]): string => {
  let latestTime = 0

  keys.forEach(key => {
    try {
      const data = localStorage.getItem(key)
      if (data) {
        const parsed = JSON.parse(data)
        if (Array.isArray(parsed) && parsed.length > 0) {
          const item = parsed[0]
          if (item.timestamp && item.timestamp > latestTime) {
            latestTime = item.timestamp
          }
        }
      }
    } catch (error) {
      // 忽略解析错误
    }
  })

  return latestTime > 0 ? new Date(latestTime).toLocaleString() : '未知'
}

// 加载用户信息和数据统计
const loadUserData = () => {
  try {
    userInfo.value = getUserInfo()
    dataStats.value = getUserDataStats()
    console.log('✅ 用户数据统计已加载:', dataStats.value)
  } catch (error) {
    console.error('❌ 加载用户数据失败:', error)
    showToast('加载数据失败')
  }
}

// 显示功能详情
const showFeatureDetail = (feature: any) => {
  selectedFeature.value = feature
  showDetailPopup.value = true
}

// 导出所有数据
const exportAllData = async () => {
  try {
    isExporting.value = true

    const userId = getCurrentUserId()
    if (!userId) {
      showToast('用户未登录')
      return
    }

    const allData: any = {}
    const userKeys = getUserDataKeys()

    userKeys.forEach(key => {
      const data = localStorage.getItem(key)
      if (data) {
        allData[key] = JSON.parse(data)
      }
    })

    const exportData = {
      userId,
      exportTime: new Date().toISOString(),
      userInfo: userInfo.value,
      dataStats: dataStats.value,
      data: allData
    }

    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json;charset=utf-8'
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `AI助手个人数据-${userId}-${new Date().toLocaleDateString()}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)

    showToast('数据导出成功')
  } catch (error) {
    console.error('❌ 导出数据失败:', error)
    showToast('导出失败')
  } finally {
    isExporting.value = false
  }
}

// 导出功能数据
const exportFeatureData = (featureName: string) => {
  try {
    const userId = getCurrentUserId()
    if (!userId) {
      showToast('用户未登录')
      return
    }

    const userKeys = getUserDataKeys()
    const featureKeys = userKeys.filter(key => key.includes(`_${featureName}_`))
    const featureData: any = {}

    featureKeys.forEach(key => {
      const data = localStorage.getItem(key)
      if (data) {
        featureData[key] = JSON.parse(data)
      }
    })

    const exportData = {
      userId,
      feature: featureName,
      exportTime: new Date().toISOString(),
      data: featureData
    }

    const blob = new Blob([JSON.stringify(exportData, null, 2)], {
      type: 'application/json;charset=utf-8'
    })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${featureName}数据-${userId}-${new Date().toLocaleDateString()}.json`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)

    showToast('功能数据导出成功')
  } catch (error) {
    console.error('❌ 导出功能数据失败:', error)
    showToast('导出失败')
  }
}

// 清空功能数据
const clearFeatureData = async (featureName: string) => {
  try {
    await showConfirmDialog({
      title: '确认清空',
      message: `确定要清空 ${featureConfig[featureName as keyof typeof featureConfig]?.displayName} 的所有数据吗？此操作不可恢复。`
    })

    const success = clearFeatureDataUtil(featureName)
    if (success) {
      showToast('数据已清空')
      loadUserData() // 重新加载数据统计
      showDetailPopup.value = false
    } else {
      showToast('清空失败')
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 显示清空确认
const showClearConfirm = async () => {
  try {
    await showConfirmDialog({
      title: '危险操作',
      message: '确定要清空所有个人数据吗？此操作不可恢复，将删除您在所有AI功能中的历史记录、设置等数据。'
    })

    // 清空所有用户数据
    const userKeys = getUserDataKeys()
    userKeys.forEach(key => localStorage.removeItem(key))

    showToast('所有数据已清空')
    loadUserData() // 重新加载数据统计
  } catch (error) {
    // 用户取消操作
  }
}

// 页面挂载时加载数据
onMounted(() => {
  loadUserData()
})
</script>

<style scoped>
.user-data-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 20px;
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

/* 用户信息卡片 */
.user-info-card {
  margin: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.user-details p {
  margin: 4px 0;
  font-size: 14px;
  color: #64748b;
}

/* 数据统计 */
.data-stats {
  margin: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.data-stats h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #64748b;
}

/* 功能数据列表 */
.feature-data-list {
  margin: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.feature-data-list h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.empty-data {
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-tip {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 8px;
}

.feature-cards {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.feature-card {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.feature-card:hover {
  background: #eff6ff;
  border-color: #667eea;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.feature-icon {
  font-size: 24px;
  margin-right: 16px;
}

.feature-info {
  flex: 1;
}

.feature-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.feature-info p {
  margin: 2px 0;
  font-size: 14px;
  color: #64748b;
}

.feature-size {
  font-size: 12px !important;
  color: #94a3b8 !important;
}

/* 数据管理操作 */
.data-actions {
  margin: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.data-actions h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 弹窗样式 */
.detail-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.popup-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.feature-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-stats {
  background: #f8fafc;
  border-radius: 12px;
  padding: 16px;
}

.detail-stat {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #e2e8f0;
}

.detail-stat:last-child {
  border-bottom: none;
}

.detail-stat .label {
  font-size: 14px;
  color: #64748b;
}

.detail-stat .value {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.data-types h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.type-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.type-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.type-name {
  font-size: 14px;
  color: #374151;
}

.type-count {
  font-size: 12px;
  color: #64748b;
  background: #e2e8f0;
  padding: 2px 8px;
  border-radius: 12px;
}

.feature-actions {
  display: flex;
  gap: 12px;
}

/* 深色模式支持 */
:global(.dark-mode) .user-data-page {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
}

:global(.dark-mode) .user-info-card,
:global(.dark-mode) .data-stats,
:global(.dark-mode) .feature-data-list,
:global(.dark-mode) .data-actions {
  background: rgba(51, 65, 85, 0.95);
  border-color: #475569;
}

:global(.dark-mode) .stat-item,
:global(.dark-mode) .feature-card {
  background: #475569;
  border-color: #64748b;
}

:global(.dark-mode) .detail-popup {
  background: #334155;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }

  .stat-item {
    padding: 12px;
  }

  .stat-number {
    font-size: 20px;
  }

  .feature-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .user-info-card {
    flex-direction: column;
    text-align: center;
  }

  .stats-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }

  .feature-card {
    padding: 12px;
  }

  .feature-icon {
    font-size: 20px;
    margin-right: 12px;
  }
}
</style>
